package com.bbseguros.pesquisador.converter;

import org.apache.log4j.Logger;

public class WebServiceClient {
	
	private static Logger logger = Logger.getLogger(WebServiceClient.class);
	
	public static final String SERVICE_AGENDAMENTO_ = "Agendamento";
	public static final String URL_SERVICE_ = "http://localhost:9080/webbbseguroauto/Service.asmx";
	
	public String callService(String service,String xml) throws Exception{
		logger.debug("[IN]");
		
		HttpWebService webService = new HttpWebService(URL_SERVICE_);
		
		webService.setService(service);					
		webService.setParam("xmlvalue", xml);
		
		String toReturn = webService.sendReceive();
		toReturn.replaceAll("&lt;", "<");
		toReturn.replaceAll("&gt;", ">");
		toReturn.replaceAll("&#13;", "");
		
		logger.debug("[RETORNO] "+toReturn);
		
		return toReturn;
	}
	
	 /**
     * @param noh
     * @param xml
     * @return
     */
    public String getXMLValue(String noh, String xml){
    	String tagStart = "<"+noh+">";
    	String tagEnd = "</"+noh+">";
    	
    	int start =  xml.indexOf(tagStart);
    	if(start == -1){
    		tagStart = "&lt;"+noh+"&gt;";
    		tagEnd = "&lt;/"+noh+"&gt;";
    		
    		start =  xml.indexOf(tagStart);
    	}    	
		int end = xml.indexOf(tagEnd);
    	
    	return xml.substring(start + tagStart.length() ,end);
    }
    
    public static String changeXMLValue(String noh, String xml, String newValue){
    	String tagStart = "<"+noh+">";
    	String tagEnd = "</"+noh+">";
    	
    	int start =  xml.indexOf(tagStart);
    	if(start == -1){
    		tagStart = "&lt;"+noh+"&gt;";
    		tagEnd = "&lt;/"+noh+"&gt;";
    		
    		start =  xml.indexOf(tagStart);
    	}    	
		int end = xml.indexOf(tagEnd);
		String result = xml;
		
		try {
			result = xml.substring(0,start + tagStart.length()) + newValue + xml.substring(end);	
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}		
    	
    	return result;
    }
   
}
